package com.ruoyi.sale.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.commodity.domain.ProductImage;
import com.ruoyi.commodity.mapper.AuthBrandMapper;
import com.ruoyi.commodity.mapper.ProductImageMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AuthBrand;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.sale.domain.*;
import com.ruoyi.sale.domain.vo.PlanProcessVo;
import com.ruoyi.sale.domain.vo.PlanVo;
import com.ruoyi.sale.mapper.ApprovalProcessMapper;
import com.ruoyi.sale.mapper.PlanMapper;
import com.ruoyi.sale.mapper.PlanProcessLogMapper;
import com.ruoyi.sale.mapper.PlanProcessMapper;
import com.ruoyi.sale.service.IPlanProcessService;
import com.ruoyi.sale.service.IPlanService;
import com.ruoyi.sale.urtl.AncestorsProcessor;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysMenuMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.template.domain.TemplateDetail;
import com.ruoyi.template.mapper.TemplateMapper;
import com.ruoyi.template.service.TemplateDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.NumberUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 销售计划Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-13
 */
@Service
public class PlanProcessServiceImpl implements IPlanProcessService {
	@Autowired
	private SysUserMapper sysUserMapper;

	@Autowired
	private PlanProcessMapper planProcessMapper;

	@Autowired
	private PlanProcessLogMapper planProcessLogMapper;

	@Autowired
	private PlanMapper planMapper;
	/**
	 * 更新审批结果
	 * @param planProcess
	 * @return 结果
	 */
	@Override
	@Transactional
	public int updatePlanProcessStatus(PlanProcess planProcess) {

		Long reviewerId = planProcess.getReviewerId();
		String planProcessStatus = planProcess.getPlanProcessStatus();
		String planProcessRemark = planProcess.getPlanProcessRemark();
		Long planId = planProcess.getPlanId();

		//更新审核流程表
		LambdaUpdateWrapper<PlanProcess> updateWrapper  = new LambdaUpdateWrapper<>();
		updateWrapper.eq(PlanProcess::getPlanId,planId);
		updateWrapper.eq(PlanProcess::getReviewerId,reviewerId);
		updateWrapper.set(PlanProcess::getPlanProcessStatus, planProcessStatus);
		updateWrapper.set(PlanProcess::getPlanProcessTime,DateUtils.getNowDate());
		updateWrapper.set(PlanProcess::getPlanProcessRemark,planProcessRemark);
		planProcessMapper.update(null,updateWrapper);

		//插入审核流程表日志
		SysUser user =  sysUserMapper.selectUserById(reviewerId);
		savePlanProcessLog(planId,planProcessStatus,user.getNickName(),planProcessRemark);

		//汇总状态，更新到销售计划表
		List<String> statuses = planProcessMapper.selectStatusesByPlanId(planId);

		String newStatus;
		if (statuses.contains("0")) {
			newStatus =  Constants.PLAN_PROCESS_STATUS_REJECTED; // 有任何一条为 "0"，则设为驳回状态
		} else if (statuses.stream().allMatch(status -> "1".equals(status))) {
			newStatus = Constants.PLAN_PROCESS_STATUS_SUCCESS; // 如果所有记录都为 "1"，则设为已审核
		} else {
			newStatus = Constants.PLAN_PROCESS_STATUS_PENDING; // 0 否则为审核中
		}

		Long reviewerUserId = planMapper.selectById(planId).getReviewerUserId();
		if(planProcessStatus.equals("1")){

			LambdaQueryWrapper<PlanProcess> qw = new LambdaQueryWrapper<>();
			qw.eq(PlanProcess::getPlanId,planId);
			qw.eq(PlanProcess::getReviewerId,reviewerId);
			PlanProcess pp = planProcessMapper.selectOne(qw);
			if(pp == null){
				throw new ServiceException("获取审核流程明细失败。");
			}
			Integer reviewerOrder = pp.getReviewerOrder();

			//通过审核，当前审核人换到上一层级
			LambdaQueryWrapper<PlanProcess> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(PlanProcess::getPlanId,planId)
					.gt(PlanProcess::getReviewerOrder,reviewerOrder)
					.orderByAsc(PlanProcess::getReviewerOrder)
					.last("LIMIT 1");
			PlanProcess nextProcess = planProcessMapper.selectOne(queryWrapper);
			if(nextProcess != null){
				reviewerUserId = nextProcess.getReviewerId();
			}

		}
		Plan p = new Plan();
		p.setId(planId);
		p.setPlanStatus(newStatus);
		p.setReviewerUserId(reviewerUserId);
		//更新销售计划表的审核状态
		return planMapper.updatePlanReviewStatus(p);
	}

	/**
	 * 插入审核流程表日志
	 * @return
	 */
	private void savePlanProcessLog(Long planId, String logStatus, String nickName, String logRemark){
		PlanProcessLog log = new PlanProcessLog(IdUtils.fastSimpleUUID(),planId,
				logStatus,nickName,logRemark,DateUtils.getNowDate());
		planProcessLogMapper.insert(log);
	}
	/**
	 * 查询审核流程
	 * @param planId
	 * @return
	 */
	@Override
	public List<PlanProcessVo> getPlanProcessList(Long planId) {
		return planProcessMapper.getPlanProcessList(planId);
	}
	/**
	 * 我已审核的销售计划
	 * @param plan
	 * @return
	 */
	@Override
	public List<PlanVo> getPlanReadyProcessList(PlanVo plan) {
		return planProcessMapper.getPlanReadyProcessList(plan);
	}
	/**
	 * 我发起的销售计划
	 * @param plan
	 * @return
	 */
	@Override
	public List<PlanVo> getPlanMyProcessList(PlanVo plan) {
		return planProcessMapper.getPlanMyProcessList(plan);
	}
}
